import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:rapid_kit/rapid_kit.dart';
import 'package:timeline_tile/timeline_tile.dart';
import '../../pages/Home/home_page.dart';
import '../../utils/LogUtils.dart';
import '../../widgets/global_widgets.dart';
import '../../widgets/lifecycle_aware.dart';

import '../../theme.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

/// 卡录像页面
class LocalReplayPage extends StatefulWidget {
  final String deviceId;
  final String deviceName;

  const LocalReplayPage(
      {super.key, required this.deviceId, required this.deviceName});

  @override
  State<LocalReplayPage> createState() => _LocalReplayPageState();
}

class _LocalReplayPageState extends LifecycleAwareState<LocalReplayPage>
    with WidgetsBindingObserver {
  static const String _tag = "_LocalReplayPage_";

  late String _deviceId;
  late String _deviceName;

  bool _audioMuted = false;

  bool _eventsLoading = true;

  late Pipe _pipe;
  late LocalReplayStream _stream;
  late Player _player;

  int _currentTimestampInMs = 0;

  LocalReplaySpeed _speed = LocalReplaySpeed.x1;

  RecordIndexPacket? _recordIndexPacket;

  DateTime _selectedDate = DateTime.now();
  final DateTime _todayDate = DateTime.now();

  bool _rendering = false;

  Future<bool> _onWillPop() async {
    // 监听返回按钮操作
    LogUtils.w("用户点击了返回按钮${_deviceName}");
    if (_deviceName == '2') {
      LogUtils.w("执行一个返回");
      Navigator.of(context).pop();
    } else {
      LogUtils.w("执行2个返回");
      Navigator.of(context).pop();
      Navigator.of(context).pop();
    }
    HomePageState.globalKeytwo.currentState?.reloadData();
    return true; // 返回true表示允许返回，返回false表示阻止返回
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: Icon(Icons.arrow_back_ios),
            onPressed: () {
              _onWillPop();
              // 返回操作
            },
          ),
          automaticallyImplyLeading: false,
          // 禁用自动生成的返回按钮
          title: Text(
            "卡录像",
            style: TextStyle(
              fontSize: 17,
              fontFamily: "PingFang SC",
              fontWeight: FontWeight.w600,
            ),
          ),
          centerTitle: true,
        ),
        body: _root(),
      ),
    );
  }

  Widget _root() {
    return LayoutBuilder(
      builder: (context, constraints) {
        double width = constraints.maxWidth;
        double height = width * 9 / 16;

        return Column(
          children: <Widget>[
            _top(width, height),
            _timestamp(),
            _middle(),
            Expanded(
              child: _bottom(),
            ),
          ],
        );
      },
    );
  }

  Widget _timestamp() {
    return Container(
      height: 25,
      width: double.infinity,
      color: const Color.fromARGB(255, 73, 113, 74),
      alignment: Alignment.center,
      child: Text(
        _currentTimestampInMs.millisecondToYYYYMMddHHmmSS(),
        style: TextStyle(
          color: Colors.white,
          fontSize: 12,
        ),
      ),
    );
  }

  IconButton _muteControl() {
    return IconButton(
      icon: Icon(
          _audioMuted ? Icons.volume_off_rounded : Icons.volume_up_rounded,
          size: 25,
          color: _audioMuted
              ? SampleThemeConfigure.colorTextPrimary
              : SampleThemeConfigure.colorTextPrimary),
      onPressed: () => _onVolumeTap(),
    );
  }

  void _onVolumeTap() {
    if (_player.isMute()) {
      _player.mute(false);
    } else {
      _player.mute(true);
    }

    setState(() {
      _audioMuted = _player.isMute();
    });
  }

  Widget _middle() {
    return Container(
      height: 100,
      width: double.infinity,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(30),
          bottomRight: Radius.circular(30),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[_muteControl(), _captureButton(), _speedButton()],
      ),
    );
  }

  IconButton _captureButton() {
    return IconButton(
      icon: const Icon(Icons.camera_alt,
          size: 25, color: SampleThemeConfigure.colorTextPrimary),
      onPressed: () {
        _player.capture();
      },
    );
  }

  IconButton _speedButton() {
    return IconButton(
      icon: const Icon(Icons.speed_rounded,
          size: 25, color: SampleThemeConfigure.colorTextPrimary),
      onPressed: () {
        _speed = _speed == LocalReplaySpeed.x1
            ? LocalReplaySpeed.x4
            : LocalReplaySpeed.x1;
        _stream.setSpeed(_speed);
      },
    );
  }

  Widget _top(double width, double height) {
    return Container(
      width: width,
      height: height,
      color: SampleThemeConfigure.colorVideoBackground,
      child: _buildVideoPlayerBody(),
    );
  }

  Widget _bottom() {
    return Column(
      children: <Widget>[
        _categoriesBar(),
        _listContainer(),
      ],
    );
  }

  Container _categoriesBar() {
    return Container(
      height: 60.0,
      padding: const EdgeInsets.symmetric(horizontal: 16.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          _datePicker(),
        ],
      ),
    );
  }

  GestureDetector _datePicker() {
    return GestureDetector(
      onTap: () async => _onPickDate(),
      child: Row(
        children: <Widget>[
          Text(
            _formattedDateString(),
            style: const TextStyle(
                fontSize: 16.0, color: SampleThemeConfigure.colorTextPrimary),
          ),
          const Padding(
            padding: EdgeInsets.only(left: 0),
            child: Icon(
              Icons.arrow_drop_down_rounded,
              size: 30,
              color: SampleThemeConfigure.colorTextPrimary,
            ),
          )
        ],
      ),
    );
  }

  String _formattedDateString() {
    String formattedDate = _selectedDate.toChineseDate();

    if (_todayDate.day == _selectedDate.day) {
      formattedDate = "$formattedDate | 今天";
    }
    return formattedDate;
  }

  void _onPickDate() async {
    DateTime? pickedDate = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(2000),
      lastDate: DateTime(2101),
    );

    if (pickedDate != null && pickedDate != _selectedDate) {
      setState(() {
        _recordIndexPacket = null;
        _selectedDate = pickedDate;
        _eventsLoading = true;

        _loadRecordIndex();
      });
    }
  }

  Widget _listContainer() {
    if (_recordIndexPacket?.list.isEmpty ?? true) {
      return _emptyTips();
    }

    return Expanded(
      child: _eventsLoading
          ? createCenterLoading(size: 20.0)
          : Padding(
              padding: const EdgeInsets.only(left: 16.0, right: 16.0),
              child: _eventList()),
    );
  }

  ListView _eventList() {
    return ListView.builder(
        itemCount: _recordIndexPacket?.list.length ?? 0,
        itemBuilder: (context, index) {
          return _buildTapItem(
            _recordIndexPacket!.list[index],
            isFirst: index == 0,
            isLast: index == _recordIndexPacket!.list.length - 1,
          );
        });
  }

  Widget _buildTapItem(RecordIndex record,
      {bool isFirst = false, bool isLast = false}) {
    return GestureDetector(
      onTap: () async {
        showToast("加载数据-请稍后");
        //
        // _stream.stop();
        _stream.seek(record.startTimestampSecond);
        // _stream.start();
      },
      child: _buildItem(record, isFirst: isFirst, isLast: isLast),
    );
  }

  Widget _buildItem(RecordIndex record,
      {bool isFirst = false, bool isLast = false}) {
    return TimelineTile(
        alignment: TimelineAlign.manual,
        lineXY: 0.3,
        isFirst: isFirst,
        isLast: isLast,
        indicatorStyle: IndicatorStyle(
          width: 30,
          iconStyle: IconStyle(
            color: Colors.white,
            fontSize: 16,
            iconData: Icons.videocam_rounded,
          ),
          color: SampleThemeConfigure.colorPrimary,
          padding: const EdgeInsets.all(6),
        ),
        beforeLineStyle: const LineStyle(
          color: SampleThemeConfigure.colorTextHint,
          thickness: 1,
        ),
        afterLineStyle: isLast
            ? null
            : const LineStyle(
                color: SampleThemeConfigure.colorTextHint,
                thickness: 1,
              ),
        startChild: Container(
          padding: const EdgeInsets.all(5),
          alignment: Alignment.centerRight,
          child: Text("${record.startTimestampSecond.toHHmmss()}-${_eventLabel(record.eventType)}",
              style: const TextStyle(
                  color: SampleThemeConfigure.colorTextHint, fontSize: 12)),
        ),
        endChild: Container(
          padding: const EdgeInsets.all(16.0),
          alignment: Alignment.centerLeft,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const SizedBox(height: 5),
              Text(
                "${_eventLabel(record.eventType)}${record.durationSecond}秒",
                style: const TextStyle(
                    color: SampleThemeConfigure.colorTextPrimary, fontSize: 12),
              ),
              const SizedBox(height: 5),
            ],
          ),
        ));
  }

  Expanded _emptyTips() {
    return Expanded(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const [
            Icon(Icons.event_note,
                size: 50, color: SampleThemeConfigure.colorPrimary),
            SizedBox(height: 10),
            Text(
              '没有录像',
              style: TextStyle(
                fontSize: 14,
                color: SampleThemeConfigure.colorPrimary,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildVideoPlayerBody() {
    return Stack(
      children: [
        Positioned.fill(
          child: Container(color: SampleThemeConfigure.colorVideoBackground),
        ),
        _player.texture(),
        if (!_rendering) bufferingWidget()
      ],
    );
  }

  Positioned bufferingWidget() {
    return Positioned.fill(
      child: Container(
        color: Colors.black54,
        child: Center(
          child: createCenterLoading(size: 20, color: Colors.white),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addObserver(this);

    _deviceId = widget.deviceId;
    _deviceName = widget.deviceName;
    _preparePlayer();

    _pipe.establish();
  }

  @override
  void dispose() {
    super.dispose();

    Logging.i(_tag, "dispose");
    _recordIndexPacket?.list.clear();

    _stream.stop();
    _player.stop();

    _player.destroy();
    _stream.destroy();

    _pipe.abolish();
    _pipe.destroy();

    WidgetsBinding.instance.removeObserver(this);
  }

  void _preparePlayer() {
    _pipe = Pipe.create(_deviceId);
    _loadRecordIndex();

    // _pipe.listen((state) {
    //   if (state == PipeState.established) {
    //     _loadRecordIndex();
    //     _stream.start();
    //     _player.start();
    //   }
    // });

    _stream = LocalReplayStream.create(_pipe);
    final providerPtr = _stream.provider(cameraIndex: 0)!;

    _player = Player.create();
    _player.onUniversalTimestamp = (timestamp) {
      // use timestamp to sync your ui, e.g. seek bar / timeline
      setState(() {
        _currentTimestampInMs = timestamp;
      });
    };
    _player.prepare(providerPtr);
    _player.onRenderState = (state) {
      setState(() {
        _rendering = state != RenderState.buffering;
      });
    };

    // 播放卡录像
    _stream.start();
    // 播放录像
    _player.start();
  }

  void _loadRecordIndex() async {
    if (_recordIndexPacket != null) {
      LogUtils.w("======退出查询====");
      return;
    }
    final date = _selectedDate.toStandardDate();
    LogUtils.w(date);
    final response = await InstructStandard.listRecords(_pipe, date);
    if (response.success) {
      _recordIndexPacket = response.data;

      // 播放SD卡视频
      if (response.data!.list.length > 0) {
        _stream.seek(response.data!.list[0].startTimestampSecond);

        // 关闭声音
        _onVolumeTap ();
      }

    }

    setState(() {
      _eventsLoading = false;
    });
  }

  String _eventLabel(int event) {
    switch (event) {
      case 0:
        return " ";
      case 1:
        return "发现移动 ";
      case 2:
        return "发现人形 ";
      case 3:
        return "发现声音 ";
      case 4:
        return "PIR ";
      default:
        return "未知 ";
    }
  }
}
